var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var pageData = false;
var store = require('mixins/store')

var _page = {
    onlineInfo: false
}


var bindEvent = function(){
    setTimeout(function(){
        // $('#send_send').find('.flex-1')[0].scrollTop=380;
        $('#express_send').find('.flex-1').animate({scrollTop: '1000px'}, 1000)
    },500)

    if (_page.onlineInfo){
        $('.dCy_branches').css('display','-webkit-box')
    }
    else {
        $('.dCy_branches').css('display','none')
    }

    $('.express').click(function(){
        router('express');
    });
    $('.send').click(function(){
        router('send/send');
    });
    $('.water').click(function(){
        router('water/send');
    });
    $('.waterCard').click(function(){
        router('water/card');
    });

    //跳转到网点介绍
    $('.default_label_branches').click(function(){
        router('uc/siteIntroduce');
    });

    //跳转切换地址
    $('#sendOrderMessage .defult_addrss_selected').click(function(){
        router('uc/addresslist',{'back':'send/send'});
    });

    //短信订阅
    $('.subscribe_btn_send').click(function(){
        router('uc/sms',{'back':'send/send'});
    });

    //end
    //此处各种dom 操作
    libs.inject()
        .js(['/js/t/jq/ui.js', 'uiLib'], express);

    function express(){
        ui.remarkTool('remarksOption', 'remarksText');
        //提交订单
        $('.send-order-btn').off();
        $('.send-order-btn').click(function(){
            // api.req('/getBookTime',{login:"f97b34f8ffc44957a2a3276da332d61c", method: 'get'},function(data){
            //     console.log(JSON.stringify(data));
            // });
            var login = SA.get('USER').login;
            // var _address = $('.send-order-address').text();
            var _address = $('.send-order-address').attr('data-id');
            var _time = $('#demo_treelist2_dummy').val();
            if(!_time){
                ui.alertBox({
                    cons: [{text:'请选择预约时间',name:"bigCon"}],
                    btns: [
                    ]
                })
            }else if(!_address){
                ui.alertBox({
                    cons: [{text:'请选择地址',name:"bigCon"}],
                    btns: [
                    ]
                })
            }else{
                var params = {
                    method: 'get',
                    login: login,
                    bookTime: _time.substring(11),  //预约时间
                    bookDate: _time.substring(0,10),  //预约时间
                    addressId: _address,  //地址
                    remark:$('.send-order-remark').val()    //备注
                };
                api.req('/weixinShippment',params,function(data){
                    if(data.orderId){
                        ui.alertBox({
                           cons: [{text:'下单已成功',name:"bigCon"},{text:'等待管家上门领件',name:"smallCon"}],
                           btns: [
                               {
                                   text: '查看订单详情',
                                   close: false,
                                   callback: function () {
                                    //    sessionStorage.setItem('sendOrderId',JSON.stringify(data));
                                       router('send/details',{back: data.orderId});
                                   }
                               }
                           ]
                       });
                   }else{
                       ui.alertBox({
                           cons: [{text:data.message,name:"littleCon"}],
                           btns: [
                           ]
                       })
                   }
                })
            }
        });
    }

    //预约时间所需要的js
    var getMobijs = SA.get('Mobiscrolljs')
    if (getMobijs && getMobijs ==='finish'){
        mobiscrolljs()
    }
    else{
        SA.set('Mobiscrolljs', mobiscrolljs)
    }
    function mobiscrolljs(){
        $('#demo_treelist2').mobiscroll().treelist({
            placeholder: '请选择服务时间',    //input的默认值
            display: 'bottom',               //弹窗的方式
            labels: ['dataTi','dataTi'],  // More info about labels: http://docs.mobiscroll.com/2-17-0/list#!opt-labels
            setText: '确定',
            cancelText: '取消'
        });
    }
};
//时间插件所需要的html结构 start
function Waytime(data){
    var abc = []
    data.map(function(item, i){
        abc.push(
            <li data-val={item} key={'waytime'+i}>
                {item}
            </li>
        )
    })
    return <ul>{abc}</ul>
}
var PeriodDate = React.createClass({
    render: function(){
        var PeriodDate_data = this.props.data;
        var times = Waytime(PeriodDate_data.times)
        return(
            <li data-val={PeriodDate_data.date}>
                {PeriodDate_data.date}
                {times}
            </li>
        )
    }
})
//end

var Send = React.createClass({
    mixins: [ItemMixin],
    willMount: function(){
        var showonline = SA.get('ONLINE2')
        var showonlineImg;
        var showonlineName;
        if(showonline){
            showonlineName = showonline.data.providerName?showonline.data.providerName:'';
            if(showonline.data.imgFileList){         //判断小区是否有图片
                if(showonline.data.imgFileList.length){
                    showonlineImg = showonline.data.imgFileList[0].extUrl
                }
            }else{
                showonlineImg = ''
            }
            return(
                <li key='dCy_branches1' className="dCy_branches">
                    <div className="dCy_pic">
                        <img src={showonlineImg} />
                    </div>
                    <div className="dCy_b_com">
                        <em>{showonlineName}</em>
                        <ul className="default_label_branches">
                            <li><a>应急复印</a></li>
                            <li><a>应急电话</a></li>
                            <li><a>便民饮水</a></li>
                            <li><a>应急上网</a></li>
                            <li><a>寻路指引</a></li>
                            <li><a>更多...</a></li>
                        </ul>
                    </div>
                </li>
            )
        }
    },
    render:function(){
        var dCydata = this.willMount()
        var sendTime = []
        var _data = this.props.data || {};
        var _dataAddress = _data.address || [];
        var _label = _data.remarkInfos?_data.remarkInfos.map(function(item,index){
            return (
                <li key={index}>{item.remarkName}</li>
            );
        }) : {};
        if(_data.appointTimes.length){
            _data.appointTimes.map(function(item,i){
                sendTime.push(
                    <PeriodDate key={'appointTimes'+i} data={item}/>
                )
            })
        }
        var showonline = SA.get('ONLINE2')
        var showonlineImg;
        if(showonline){
            if(showonline.data && showonline.data.imgFileList && showonline.data.imgFileList.length){     //判断小区是否有图片
                showonlineImg = showonline.data.imgFileList[0].extUrl
            }else{
                showonlineImg = ''
            }
        }
        var onlineStatus;
        if(_data.user.isReceiveSms == true){
            onlineStatus = '短信已订阅'
        }else{
            onlineStatus = '短信订阅'
        }
        return (
            <div className="expressWarp send-main flex flex-v" id="express_send">
                <div className="flex-1 f-oTouch">
                    <div className="nav box-shadow">
                        <div className="express">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/express.png" alt="" />
                                </div>
                                <div className="nav-text"><span>我要收件</span></div>
                            </a>
                        </div>
                        <div className="send">
                            <a href="javascript:;" className="active">
                                <div className="nav-icon">
                                    <img src="/images/send.png" alt="" />
                                </div>
                                <div className="nav-text"><span>快递寄件</span></div>
                            </a>
                        </div>
                        <div className="water">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/water.png" alt="" />
                                </div>
                                <div className="nav-text"><span>预约送水</span></div>
                            </a>
                        </div>
                        <div className="waterCard">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/waterCard.png" alt="" />
                                </div>
                                <div className="nav-text"><span>购买水卡</span></div>
                            </a>
                        </div>
                    </div>
                    <div className="u-mt-15 default_pd016 default_community box-shadow">
                        <h3>社区便民</h3>
                        <ul>
                            {dCydata}
                            <li className="dCy_notice">
                                <div className="dCy_pic">
                                    <img src="/images/img_tu2.png" alt="" />
                                </div>
                                <div className="dCy_b_com">
                                    <div className="dCy_n_com">
                                        <em>小区公告</em>
                                        <p>左邻右里最新动态信息</p>
                                    </div>
                                    <div className="f_submit">
                                        <a className="f_btn subscribe_btn subscribe_btn_send"><i className="iconfont icon-975shoujitongxinlu"></i>{onlineStatus}</a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>

                    <div id="sendOrderMessage">
                        <div className="default_pd016 mT02 box-shadow">
                            <div className="defult_addrss_selected">
                                <p><label>姓名</label><span>{_dataAddress.contact?_dataAddress.contact:'请输入收件人姓名'}</span></p>
                                <p><label>电话</label><span>{_dataAddress.contactPhone?_dataAddress.contactPhone:'请输入收件人电话'}</span></p>
                                <p><label>地址</label><span data-id={_dataAddress.id} className="send-order-address">{_dataAddress.fullAddress?_dataAddress.fullAddress:'请选择小区'}</span></p>
                                <i className="iconfont icon-xiangyou"></i>
                            </div>
                        </div>

                        <div className="default_pd016 box-shadow u-mt-15 m-form" id="demo_cont_treelist">
                            <label>预约时间</label>
                            <ul id="demo_treelist2" className="u-none">
                                {sendTime}
                            </ul>
                        </div>

                        <div className="default_pd016 mT014 default_note">
                            <div className="d_note_head">
                                <label>备注</label>
                                <textarea id="remarksText" className="send-order-remark" placeholder="添加备注信息"></textarea>
                            </div>
                            <ul className="default_label" id="remarksOption">
                                {_label}
                            </ul>
                        </div>
                    </div>

                    <div className="u-mb"></div>
                </div>

                <div className="default_foot">
                    <div className="dF_total dF_check">
                        <p><i className="iconfont icon-juxing10kaobei9"></i>我同意<i>《大白快递运单条款》</i></p>
                    </div>
                    <div className="send-order-btn">
                        <a href="javascript:;">提交订单</a>
                    </div>
                </div>

            </div>
        )
    }
});

function wsAdressBack(){
    var _this = this;
    //获取用户信息 和 标签
    var login = SA.get('USER').login;
    var send_post = {
        login: login,
        method:'get'
    }

    api.req('/onlineInfo',{login: SA.get('USER').login, method:'get'}, function(data){
        if(!data.code){
            _page.onlineInfo = true;
            SA.setter('ONLINE2', {data: data})

            api.req('/userInfoNotes', send_post, function (data){
                if(data.code == '114000' || data.code == '115000'){
                    router('uc/location')
                }else{
                    pageData = data;
                    _this.main(_this,data);
                }
            });
        }
    })

}

function start(name){
    return pages.new({
        boot:function(){},
        trigger:function(){
            this.libs.changeTitle('服务');    //更改当前页面标题
            wsAdressBack.call(this)
        },
        goback: function(){
            var _pre = router.pre();
            if (_pre.hash==='login'){
                router.cb=function(){
                    if (wx){
                        wx.closeWindow()
                    }
                }
            }
            else {
                router.cb=function(){
                    router.goback()
                }
            }
        },
        main: function(self,data){
            this.render(
            <Send itemDefaultMethod={bindEvent} data={data} />,
                document.getElementById(name)
            )
        },
        end:function(){
            SA.deleter('ONLINE2')
            $('.ab_cover,.m-box').remove(); //关闭弹窗
            React.unmountComponentAtNode(document.getElementById(name))
        }
    })
}

module.exports = start;
